package com.kun.kunkunmall.order.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.kun.kunkunmall.order.config.AlipayConfig;
import com.kun.kunkunmall.order.service.AliPayService;
import org.springframework.stereotype.Service;

@Service
public class AliPayServiceImpl implements AliPayService {

    /**
     * 调取支付宝接口 web端
     */
    DefaultAlipayClient alipayClient = new DefaultAlipayClient(
            AlipayConfig.URL,AlipayConfig.APPID,AlipayConfig.RSA_PRIVATE_KEY,"json",
            AlipayConfig.CHARSET,AlipayConfig.ALIPAY_PUBLIC_KEY,AlipayConfig.SIGNTYPE);


    @Override
    public String webPagePay(String outTradeNo, String totalAmount, String subject) throws AlipayApiException {
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        /** 同步通知，支付完成后，支付成功页面*/
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        /** 异步通知，支付完成后，需要进行的异步处理*/
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        alipayRequest.setBizContent("{" +
                "    \"out_trade_no\":\""+outTradeNo+"\"," +
                "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                "    \"total_amount\":"+totalAmount+"," +
                "    \"subject\":\""+subject+"\"," +
                "    \"timeout_express\":\"1m\"," + // 支付宝的收单功能，超过多长时间不支付就收单，关闭交易，因为我们设置的订单有效期为1m。
                "    \"body\":\""+"商品介绍"+"\"," +
                "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}" );
        /**转换格式*/
        String result = alipayClient.pageExecute(alipayRequest).getBody().replace('\"','\'').replace('\n',' ');
        return result;
    }
}
